<template>
  <div label="团队列表" name="详情">
    <el-row>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="">
          <el-checkbox v-model="isadmin" :label="isadminLabel" />
        </el-form-item>
        <el-form-item label="团队名">
          <el-input
            v-model.lazy="like"
            placeholder="请输入团队名称、ID"
            clearable
          />
        </el-form-item>
        <el-form-item label="团队等级">
          <el-select v-model="form.grade" clearable :style="{ width: '200px' }">
            <el-option label="免费客户（Level 0）" :value="0"></el-option>
            <el-option label="黄金客户（Level 1）" :value="1"></el-option>
            <el-option label="铂金客户（Level 2）" :value="2"></el-option>
            <el-option label="钻石客户（Level 3）" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Saas域名">
          <el-input
            v-model.trim.lazy="form.teamkey"
            placeholder="请输入Saas团队域名"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="start">查询</el-button>
        </el-form-item>
      </el-form>
      <Addteam
        v-bind="{ ID: IID, team: team, create, closed, packegekey }"
      ></Addteam>
    </el-row>

    <el-table
      :data="tableData"
      height="80vh"
      border
      class="cu"
      style="width: 100%"
      @sort-change="sortchange"
      @cell-click="() => {}"
      @selection-change="handleChange"
      :highlight-current-row="!!userhandleCurrentChange"
      @current-change="
        (e) =>
          p.userhandleCurrentChange
            ? userCurrentChange(e)
            : $router.push({ name: '团队', params: { ID: e.ID } })
      "
    >
      <el-table-column
        label="团队id"
        prop="ID"
        sortable
        width="100"
      ></el-table-column>
      <el-table-column label="团队名称" prop="name" sortable></el-table-column>
      <el-table-column
        label="创建者"
        prop="userid"
        :formatter="({ user }) => user?.name || ''"
        sortable
        width="100"
      >
      </el-table-column>
      <el-table-column label="Sass域名" prop="teamkey" width="120">
        <template #default="{ row }">
          <el-tooltip content="" placement="top">
            <template #content> 点击跳转：{{ getSaasUrl(row) }} </template>
            <el-link
              type="danger"
              target="_blank"
              :href="getSaasUrl(row)"
              @click.stop
            >
              <el-text type="danger">{{ row.teamkey }}</el-text>
            </el-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="数据大屏" prop="teamkey" width="120">
        <template #default="{ row }">
          <el-tooltip content="" placement="top">
            <template #content> 点击跳转：{{ getteamchatUrl(row) }} </template>
            <el-link
              type="danger"
              target="_blank"
              :href="getteamchatUrl(row)"
              @click.stop
            >
              <el-text type="danger">点击跳转</el-text>
            </el-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        label="等级"
        prop="grade"
        sortable
        :formatter="({ grade }) => gradez[grade || 0]"
        width=""
      >
      </el-table-column>
      <el-table-column label="公告" prop="info" width=""></el-table-column>
      <el-table-column
        :label="isadminLabel"
        prop="isadmin"
        :formatter="({ isadmin }) => (!isadmin ? '是' : '否')"
        width="120"
      >
      </el-table-column>
      <el-table-column
        prop="createdAt"
        label="创建时间"
        :formatter="({ createdAt }) => formatter(createdAt)"
        sortable
        width="110"
      >
      </el-table-column>
      <el-table-column
        prop="updatedAt"
        label="修改时间"
        :formatter="({ updatedAt }) => formatter(updatedAt)"
        sortable
        width="110"
      >
      </el-table-column>
      <el-table-column
        v-if="!tenant_id"
        prop="tenant_id"
        label="tenant_id"
        width="100"
      >
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button
            size="default"
            type="primary"
            @click.stop="IID = scope.row.ID"
            >修改</el-button
          >
          <el-button
            size="default"
            type="danger"
            @click.stop="del(scope.row.ID)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pager"
      :hide-on-single-page="false"
      :page-size="Number(limit)"
      :total="count"
      :page-sizes="pageSizes"
      layout="total,sizes,prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, inject, onMounted, reactive, ref, watch } from "vue";
import { useStore } from "vuex";
import { asyncadmindelteam } from "../../../api";
import { Storekey } from "../../../interface";
import study from "../../../mysql_interface/studycodemodel";
import { toLocaleDateString } from "../../../util/time";
import Addteam from "./addteam.vue";
import { hterobotSaasDomain, mkxSaasDomain, xhsdSaasHostname } from "../../../util/data";
// 码客行

const tenant_id = inject<string | undefined>("tenant_id", undefined);
const isAdmin = tenant_id ? true : false;

const p = defineProps<{
  tablekey?: Array<keyof study.Iteam>;
  handleSelectionChange?: (n: study.Iteam[]) => void;
  selectarr?: number[];
  userhandleCurrentChange?: (n: study.Iteam) => void;
}>();

const defaultTeamInfo: study.Iteam = {
  name: undefined,
  info: undefined,
  description: undefined,
  textarea: undefined,
  userid: undefined,
  user: {},
  other: {
    disabledNav: [],
    disabledUserMenu: [],
    // 是否显示远程评测
    showRemotejudge: false,
    // 思路提示
    ideaTips: false,
    // 代码协助
    codeHelp: false,
    // AI分析比赛
    activitySummarize: false,
    // AI分析比赛成员
    activityUserSummarize: false,
  },
  // 重置老oj icon 和 teamkey
  icon: undefined,
  teamkey: undefined,

  // isadmin: isAdmin,
  color: "-cheng",
  isranking: true,
  grade: 0,
  // 码客行
  tenant_id,
} as study.Iteam;

const gradez = [
  "免费客户（Level 0）",
  "黄金客户（Level 1）",
  "铂金客户（Level 2）",
  "钻石客户（Level 3）",
];

const sortable = ref("DESC");
const IID = ref<number | undefined>();
const offset = ref(0);
const limit = ref(20);
const pageSizes: number[] = [limit.value, 50, 100, 200, 400, 500];
const order = ref("ID");
const like = ref("");
const teamkey = ref("");
const form = reactive<study.Iteam>({
  isadmin: isAdmin,
});

const isadmin = computed({
  get() {
    return !form.isadmin;
  },
  set(v) {
    form.isadmin = !v;
  },
});
const isadminLabel = computed(() => {
  return "是否官方创建";
});

const store = useStore(Storekey);
const packegekey = computed(() => {
  return store.state.packegekey?.rows;
});
const tableData = computed<study.Iteam[]>(() => {
  return store.getters.getteam;
});

const team = computed<study.Iteam>(() => {
  // return tableData.value.find((v) => v.ID === IID.value) || { ...defaultTeamInfo };
  //
  if (IID.value) {
    let selectedTeam = tableData.value.find((v) => v.ID === IID.value) || {
      ...defaultTeamInfo,
    };
    if (!selectedTeam.other) {
      // 是否初始化   disabledNav: [],disabledUserMenu: [],
      selectedTeam.other = { showRemotejudge: false };
    }
    return selectedTeam;
  } else {
    return defaultTeamInfo;
  }
});

const count = computed<number>(() => {
  return store.getters.getteamcount;
});

function create() {
  IID.value = undefined;
}

onMounted(() => {
  store.dispatch("actionpackegekey");
  start();
});

async function start() {
  console.log("tenant_id", tenant_id);
  try {
    let z;
    if (like.value) {
      // number
      if (!isNaN(Number(like.value)) && like.value !== "") {
        z = ["ID", Number(like.value)]; // 确保存入的是数值
      } else {
        z = ["name", like.value];
      }
    }
    store.dispatch("actionteam", {
      _limit: limit.value,
      _offset: offset.value,
      _order: order.value,
      _sortable: sortable.value,
      _like: z,
      // teamkey: teamkey.value,
      ...form,
      // 码客行
      tenant_id,
    });
  } catch (e: any) {
    ElMessage.error(e);
  }
}

async function closed() {
  await start();
  // IID.value = !IID.value;
  IID.value = undefined;
}

function handleCurrentChange(val: number) {
  offset.value = limit.value * (val - 1);
}
const handleSizeChange = (val: number) => {
  limit.value = val;
  start();
};
function sortchange(row: { prop: string; order: string }) {
  const { prop } = row;
  if (row.order == "descending") {
    sortable.value = "DESC";
  } else {
    sortable.value = "ASC";
  }
  order.value = prop;
}

function handleChange(data: study.Iteam[]) {
  if (p.handleSelectionChange) p.handleSelectionChange(data);
}
function userCurrentChange(data: study.Iteam) {
  if (p.userhandleCurrentChange) p.userhandleCurrentChange(data);
}

async function del(ID: any) {
  ElMessageBox.confirm("确定要删除团队？", "提示").then(async () => {
    try {
      await asyncadmindelteam({ ID });
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      await start();
    } catch (e: any) {
      ElMessage({
        message: e,
        type: "error",
      });
    }
  });
}

function formatter(updatedAt?: string | number | Date) {
  return toLocaleDateString(updatedAt);
}
'isMkx'
function getSaasUrl(row: study.Iteam) {
  if (row.teamkey) {
    // const mkxSaasDomain = `accoders.stemworld.top`
    // const mkxSaasDomain = `stem.accoders.cn`
    // const hterobotSaasDomain = `stem.hterobot.com`
    // TODO 码客行
    // console.log("tenant_id", row.tenant_id, tenant_id)
    if(row.tenant_id === '码客行' || tenant_id === '码客行'){
      return `https://${row.teamkey}.${mkxSaasDomain}`;
    }
    if(row.tenant_id === '新华书店' || tenant_id === '新华书店'){
      return `https://${row.teamkey}.${xhsdSaasHostname}`;
    }
    return `https://${row.teamkey}.${hterobotSaasDomain}`;
    // return row.tenant_id === "码客行"
    //   ? `https://${row.teamkey}.${mkxSaasDomain}`
    //   : `https://${row.teamkey}.${hterobotSaasDomain}`;
    // return tenant_id
    //   ? `https://${row.teamkey}.${mkxSaasDomain}`
    //   : `https://${row.teamkey}.${hterobotSaasDomain}`;
  }
}

function getteamchatUrl(row: study.Iteam) {
  return `/teamchart?teamid=${row.ID}`;
}

watch(
  () => [limit.value, offset.value, order.value, sortable.value, teamkey.value],
  () => {
    start();
  }
);

watch(
  () => like.value,
  () => {
    limit.value = 20;
    offset.value = 0;
  }
);
</script>
